//
//  ComposeTextView.swift
//  MyWeiBo
//
//  Created by mac on 15/3/13.
//  Copyright (c) 2015年 gpr. All rights reserved.
//

import UIKit

class ComposeTextView: UITextView {

    // 字体大小
    let fontSize:CGFloat = 18
    // 提示文字的大小
    let placeHoderText = "分享新鲜事..."
    // 输入框最大能够显示多少个文字
    let maxTextCountInTextView = 140
    
    weak var placeHoderTextlabel: UILabel?
    
    override func awakeFromNib() {
        setUpPlaceHoderText()
    }
    
    func setUpPlaceHoderText() {
        // 保证textView文字能够滑动
        let textFont = UIFont.systemFontOfSize(fontSize)
        alwaysBounceVertical = true
        font = textFont
        let label = UILabel()
        label.font = textFont
        label.text = placeHoderText
        label.frame = CGRectMake(5, 8, 0, 0)
        label.sizeToFit()
        label.textColor = UIColor.lightGrayColor()
        self.addSubview(label)
        self.placeHoderTextlabel = label
    }

    func inputEmoticon(emoticon: Emoticon) {
        // 先判断 emoji
        if emoticon.type == 1 {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        // 取出用户当前的文本
        var attributeText = NSMutableAttributedString(attributedString: self.attributedText)
        // 将表情变成富文本
        let text = EmoticonTextAttachment.attributedStringWithEmoticon(emoticon, lineHeight: font.lineHeight)
        attributeText.replaceCharactersInRange(selectedRange, withAttributedString: text)
        // 重置文本属性
        let range = NSMakeRange(0, attributeText.length)
        // 替换前纪录光标位置
        let location = selectedRange.location
        attributeText.addAttribute(NSFontAttributeName, value: font, range: range)
        // 把原有的文本整个替换
        self.attributedText = attributeText
        // 重置光标
        selectedRange = NSMakeRange(location + 1, 0)
    }
    
    
    func rawTextString() -> String {
        var rawString = String()
        let range = NSMakeRange(0, attributedText.length)
        attributedText.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions.allZeros) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? EmoticonTextAttachment {
                rawString += attachment.emoticonString!
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                rawString += str
            }
        }
//        println("微博内容 --" + rawString)
        return rawString
    }
}
